module Syspec
  class Core
    class << self

      attr_accessor :options, :registry

      def run(args)

        self.registry = {}
        self.options = Options.new(args)

        if File.exists? options.file
          load options.file
        else
          puts options.parser
          puts "ERROR: #{File.expand_path(options.file)} does not exist.".bold.red
          exit 1
        end
        
        if registry.empty?
          puts options.parser
          puts "ERROR: No checks specified!".bold.red
          exit 1
        end
        
        execute_from_registry(options.checks)
      end
      
      def register(domain, &block)
        registry[domain] ||= []
        registry[domain] << block
      end
      
      def execute_from_registry(checks = :everything)
        if checks == :everything
          execute(registry)
        else
          execute(registry.select { |(domain, blocks)| checks.map(&:to_sym).include? domain })
        end
      end
      
      def execute(domains)
        domains.each do |(domain, blocks)|
          blocks.each { |block| Syspec::Task.new(domain, &block) }
        end
      end

    end
  end
end